package com.srolorz.fmtp.thread.pool.executor.factory;

import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger;

public class DefaultThreadFactory extends AbstractThreadFactory {
    public static DefaultThreadFactory builder() {
        return new DefaultThreadFactory();
    }

    @Override
    public AbstractThreadFactory setThreadNamePrefix(String threadNamePrefix) {
        Optional.ofNullable(threadNamePrefix).ifPresent(thread -> {
            super.setThreadNamePrefix(thread);
        });
        return this;
    }

    @Override
    public AbstractThreadFactory setThreadGroup(ThreadGroup threadGroup) {
        Optional.ofNullable(threadGroup).ifPresent(group -> {
            threadGroupMap.remove(this.getThreadGroup().getName());
            int poolNum = poolNumber.get();
            poolNumber.set(poolNum - 1);
            super.setThreadGroup(group);
        });
        threadGroupMap.put(this.getThreadGroup().getName(), new AtomicInteger(1));
        return this;
    }

    @Override
    public Thread newThread(Runnable r) {
        StringBuffer poolName = new StringBuffer(this.getThreadGroup().getName());
        poolName.append("-")
                .append(this.getThreadNamePrefix())
                .append(threadGroupMap.get(this.getThreadGroup().getName()).getAndIncrement());
        Thread thread = new Thread(this.getThreadGroup(), r, poolName.toString(), 0L);
        if(thread.isDaemon()){
            thread.setDaemon(false);
        }
        if(thread.getPriority() != 5){
            thread.setPriority(5);
        }
        return thread;
    }
}
